'use client';
import Image from 'next/image';
import { useEffect, useState, useRef, memo } from 'react';
import dayjs from 'dayjs';
import noVideo from '@/img/wms/noVideo.png';
import styles from '../../pages.module.scss';

const EzuikitPlayer = (props: {
  id: number;
  warehouseMontiorInfo: any;
  cameraList: any;
}) => {
  const [hasVideo, setHasVideo] = useState(false);
  const player = useRef<any>();
  const timer = useRef<any>();

  const initVideo = async (warehouseMontiorInfo: any, cameraList: any) => {
    const EZUIKit = (await import('ezuikit-js')) as unknown as any;

    const { accessToken, areaDomain } =
      warehouseMontiorInfo?.otherDataMap || {};
    const cameraNetworkAddress = cameraList[0]?.cameraNetworkAddress;

    player.current = new EZUIKit.EZUIKitPlayer({
      id: `ezuikit-player-${props.id}`,
      url: cameraNetworkAddress,
      accessToken: accessToken,
      useHardDev: true,
      height: 425,
      width: 705,
      env: {
        domain: areaDomain,
      },
      handleSuccess: function (res: any) {
        setHasVideo(true);
      },
      handleError: function (res: any, error: any) {
        setHasVideo(false);
        if (timer.current) {
          clearTimeout(timer.current);
        }
        player.current?.stop();
        timer.current = setTimeout(() => {
          
          const yesterday = dayjs().subtract(1, 'day').format('YYYYMMDDHHmmss');
          // 开始时间需要重新计算
          const newUrl = cameraNetworkAddress.replace(
            /(begin=)([^&]*)/,
            `$1${yesterday}`,
          );
          player.current?.play({
            url: newUrl,
            accessToken: accessToken,
          });
          // initVideo(warehouseMontiorInfo, cameraList);
        }, 6000 * 1);
      },
    });
  };

  useEffect(() => {
    initVideo(props.warehouseMontiorInfo, props.cameraList);
  }, []);

  return (
    <div className={styles.playerBox}>
      <div
        id={'ezuikit-player-' + props.id}
        style={{ width: '100%', height: 425, borderRadius: 10 }}
      ></div>
      {!hasVideo && (
        <Image
          src={noVideo}
          style={{
            position: 'absolute',
            width: '100%',
            height: 425,
            borderRadius: 10,
            left: 0,
            top: 0,
          }}
          alt="noVideo"
        />
      )}
    </div>
  );
};

export default memo(EzuikitPlayer);
